import os
import sys
import subprocess
from PySide6.QtWidgets import (
    QApplication,
    QWidget,
    QPushButton,
    QHBoxLayout,
    QMessageBox,
)
from PySide6.QtGui import QKeySequence, QShortcut

SRC_DIR = os.path.join(os.path.dirname(__file__))

TOOLS = {"PDF工具": "pdf_tools.py", "二维码工具": "QRcode.py", "计数器": "Counter.py"}


class ToolLauncher(QWidget):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("工具展示")
        layout = QHBoxLayout()
        for tool_name, file_name in TOOLS.items():
            btn = QPushButton(tool_name)
            btn.clicked.connect(lambda checked, f=file_name: self.run_tool(f))
            layout.addWidget(btn)
        self.setLayout(layout)

        # 添加快捷键Esc退出程序
        QShortcut(QKeySequence("Esc"), self, self.close)

    def run_tool(self, filename):
        filepath = os.path.join(SRC_DIR, filename)
        if not os.path.exists(filepath):
            QMessageBox.critical(self, "错误", f"文件不存在: {filepath}")
            return
        # 运行PySide6程序
        try:
            subprocess.Popen([sys.executable, filepath])
        except Exception as e:
            QMessageBox.critical(self, "错误", f"无法运行程序: {e}")


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = ToolLauncher()
    window.show()
    sys.exit(app.exec())
